<template>
  <div class="addressEdit">
    <!-- 引入公共头部 -->
    <NavBar title="地址修改" url="/user/address" back/>
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-delete
      show-set-default
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>
<script>
import { Toast } from 'vant'
import NavBar from '../../components/common/NavBar.vue'
import userApi from '../../api/user'
import areaData from '@/assets/json/area.json'
export default {
  name: 'addressEdit',
  data () {
    return {
      areaList: areaData.re,
      searchResult: [],
      addressInfo: {id: 0, name: '', tel: '', province: '', city: '', county: '', addressDetail: '', isDefault: '', areaCode: ''}
    }
  },
  mounted () {
    this.getAddressById()
  },
  methods: {
    // 通过id获取地址
    getAddressById: function () {
      const _this = this
      userApi.getAddress(this.$route.query.addressId).then(function (res) {
        if (res.data.success) {
          _this.addressInfo.id = res.data.re.id
          _this.addressInfo.name = res.data.re.receiver
          _this.addressInfo.tel = res.data.re.telephone
          _this.addressInfo.province = res.data.re.province
          _this.addressInfo.city = res.data.re.city
          _this.addressInfo.county = res.data.re.district
          _this.addressInfo.addressDetail = res.data.re.addrDetail
          _this.addressInfo.areaCode = res.data.re.areaCode
          _this.addressInfo.isDefault = (res.data.re.isDefault === 1)
        } else {
          Toast.fail('获取地址信息失败！')
          _this.$router.push('/user/address')
        }
      }).catch(function () {
        Toast.fail('获取地址信息失败！')
        _this.$router.push('/user/address')
      })
    },
    onSave (val) {
      const _this = this
      userApi.updateAddress(val).then(function (res) {
        if (res.data.success) {
          Toast.success('保存成功！')
          _this.$router.push('/user/address')
        } else {
          Toast.fail('保存失败！')
        }
      }).catch(function () {
      })
    },
    onDelete (val) {
      const _this = this
      userApi.deleteAddress(val).then(function (res) {
        if (res.data.success) {
          Toast.success('删除成功！')
          _this.$router.push('/user/address')
        } else {
          Toast.fail(res.data.msg)
        }
      }).catch(function () {
      })
    }
  },
  components: {
    NavBar
  }
}
</script>
